package fr.neyb.bernouilli.problem020;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Simplifier {

	List<Integer> ints = new ArrayList<>();

	public Simplifier(int factorial) {
		for (int i = 1; i <= factorial; ++i) {
			ints.add(i);
		}

		simplify10(factorial);
		simplify2_5(factorial);
	}

	private void simplify10(int factorial) {
		int curr = factorial;
		while ((curr = getBiggerMultInInts(10, curr)) > 0) {
			if (ints.remove((Integer) curr)) {
				ints.add(curr / 10);
			}
		}
	}

	private void simplify2_5(int factorial) {

		int curr2Mult = factorial;
		int curr5Mult = factorial;

		while ((curr5Mult = getBiggerMultInInts(5, curr5Mult)) > 0
				&& (curr2Mult = getBiggerMultInInts(2, curr2Mult)) > 0) {
			if (ints.remove((Integer) curr2Mult))
				ints.add(curr2Mult / 2);
			if (ints.remove((Integer) curr5Mult))
				ints.add(curr5Mult / 5);
		}
	}

	public BigInteger getmult() {
		BigInteger res = new BigInteger("1");
		for (Integer i : ints) {
			if (i == 0)
				return new BigInteger("0");
			res = res.multiply(new BigInteger(i.toString()));
		}
		return res;
	}

	private int getBiggerMultInInts(int multOf, int below) {
		Collections.sort(ints);
		for (int i = ints.size() - 1; i >= 0; --i)
			if (ints.get(i) % multOf == 0 && ints.get(i) <= below)
				return ints.get(i);
		return -1;
	}
}
